package br.com.mural.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Conexao {
	// nome da unidade de persistencia definida no persistence.xml
	private static final String UNIT_NAME = "WebServiceMural";

	public static EntityManager entityManager;
	private static EntityManagerFactory factory;

	public Conexao() {
		entityManager = getEntityManager();

	}

	public static EntityManager obterConexao() {
		if (entityManager == null) {
			entityManager = getEntityManager();
		}
		return entityManager;
	}

	public static void fecharConexao() {
		factory.close();
		entityManager.close();
	}

	public static EntityManager getEntityManager() {
		factory = null;
		entityManager = null;
		try {
			//Obtem o factory a partir da unidade de persist ncia.
			factory = Persistence.createEntityManagerFactory(UNIT_NAME);
			//Cria um entity manager.
			entityManager = factory.createEntityManager();
			//Fecha o factory para liberar os recursos utilizado.
		} catch (Exception e) {
			System.out.println("Erro: " + e.getMessage());
		}
		return entityManager;
	}
}
